/*
 * UDPSocket.cpp
 *
 *  Created on: 20/06/2014
 *      Author: Vitor
 */

#include "UDPSocket.h"

UDPSocket::UDPSocket(short port) {
	socket = SDLNet_UDP_Open(port);
}

UDPSocket::~UDPSocket() {
	SDLNet_UDP_Close(socket);
}

void UDPSocket::send(const std::vector<char>& bytes, std::string ip_address,
		short port) {
	UDPpacket* packet = SDLNet_AllocPacket(bytes.size());
	IPaddress ip_to_send;

	if ((SDLNet_ResolveHost(&ip_to_send, ip_address.c_str(), port)) < 0) {
		fprintf(stderr, "SDLNet_ResolveHost(%s, %u): %s.\n", ip_address.c_str(),
				port, SDLNet_GetError());
		exit(1);
	}

	packet->address = ip_to_send;
	packet->len = bytes.size();
	for (unsigned int i = 0; i < bytes.size(); i++) {
		packet->data[i] = (Uint8) bytes[i];
	}

	SDLNet_UDP_Send(socket, -1, packet);

	SDLNet_FreePacket(packet);
}

bool UDPSocket::recv(int max_size, UDPPacket& storing_packet) {
	UDPpacket* packet = SDLNet_AllocPacket(max_size);

	if (!SDLNet_UDP_Recv(socket, packet)) {
		SDLNet_FreePacket(packet);
		return false;
	}

	storing_packet.host_ip = packet->address.host;
	storing_packet.port = packet->address.port;
	storing_packet.bytes.insert(storing_packet.bytes.end(), packet->data,
			packet->data + packet->len);

	SDLNet_FreePacket(packet);

	return true;
}
